import router from './router'
import store from './store'
import NProgress from 'nprogress' 
import 'nprogress/nprogress.css' 
import { getToken } from '@/utils/auth' 
import getPageTitle from '@/utils/get-page-title'
import { canTurnTo } from '@/utils/access'
import { has } from 'core-js/fn/dict'

NProgress.configure({ showSpinner: false }) 

const turnTo = (to, access, next) => {
  var can = canTurnTo(to.name, access, router.options.routes)
  if (can) next()
  else next({ replace: true, name: 'error_401' })
}

router.beforeEach(async (to, from, next) => {            
  NProgress.start()                                     
  document.title = getPageTitle(to.meta.title)          


  const hasToken = getToken()                           
  if (hasToken) {                                       
    console.log(to.path)
      next({ path: '/' })                              
      NProgress.done()                                  
    } else {                                            
      var userInfo = store.state.user.name              
      if (userInfo) {                                  
        turnTo(to, store.state.user.access, next)       
      } else {                                           
        console.log('登录成功，已经有token，',
          '但是还没有用户信息，准备获用户信息')            
        
        store.dispatch('user/getInfo').then(user => {   
          turnTo(to, user.access, next)                
        })                                              
          .catch(() => {                              
            console.log('获取 失败！！')                   
            store.dispatch('user/resetToken')             
            next('/login')                                
          })                                              
      }                                                    
    }                                                     
  }                                                      
  else({
    if (to.path === '/login') 
      next()
    } else {
      next(`/login`)
      NProgress.done()
    }
  }
})                                                        

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})

